package com.merchant.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.tomcat.jni.Address;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: merchant-register
 * @description: 商户名称处理类
 * @author: Vincent
 * @create: 2019-03-01 17:01
 **/
@Component("merchantNameHelper")
public class MerchantNameHelper implements MerchantNameHelperFace {
    private Logger log = LoggerFactory.getLogger("MerchantNameHelper");

    @Autowired
    private AddressHelper addressHelper;

    private static final String SY_CACHE_SHOP_INFO = "MERCHANT_NAME_HELPER_SY_SHOP";

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 格式化商户名称
     *
     * @param name         名称
     * @param originalName 原始名称
     * @return String
     */
    @Override
    public String formatMerchantName(String name, String originalName) {
        // 过滤关键词
        if (name.contains("车臣")) {
            name = name.replaceAll("车臣", "CC");
        }
        if (name.contains("武侯祠")) {
            name = name.replaceAll("武侯祠", "WHC");
        }
        if (name.contains("大师")) {
            name = name.replaceAll("大师", "DS");
        }
        if (name.contains("按摩")) {
            name = name.replaceAll("按摩", "AM");
        }
        if (name.contains("无界")) {
            name = name.replaceAll("无界", "WJ");
        }
        if (name.contains("私服")) {
            name = name.replaceAll("私服", "SF");
        }
        if (name.contains("回回")) {
            name = name.replaceAll("回回", "HH");
        }
        if (name.contains("清真")) {
            name = name.replaceAll("清真", "QZ");
        }
        if (name.contains("&")) {
            name = name.replaceAll("\\&", "");
        }

        // 截取字母
        if (name.length() >= 10) {
            name = handleLetter(name);
        }
        // 去掉"直营店"
        if (name.length() >= 10) {
            name = name.replaceAll("直营店", "");
        }
        // 去掉"店"
        if (name.length() >= 10) {
            name = name.replaceAll("店", "");
        }
        // 去掉"中心"
        if (name.length() >= 10) {
            name = name.replaceAll("中心", "");
        }
        // 去掉括号，截取字母
        if (name.length() >= 10) {
            String temp = name.replaceAll("（", "");
            temp = temp.replaceAll("（", "");
            temp = temp.replaceAll("）", "");
            temp = temp.replaceAll("\\(", "");
            temp = temp.replaceAll("\\)", "");
            if (temp.length() < 10) {
                name = temp;
            }
        }

        // 去掉括号和里面内容，
        if (name.length() >= 10) {
            name = originalName.replaceAll("（.+）", "");
            name = name.replaceAll("\\(.+\\)", "");
        }
        // 截取名称中的前9个字符
        if (name.length() >= 10) {
            name = name.substring(0, 9);
        }

        // 特殊处理
        if (name.equals("7天连锁酒店")) name = "7天连锁酒店二";
        if (name.equals("SELECTED")) name = "SELECTED2";
        if (name.equals("starfish蓝")) name = "starfis2蓝";
        if (name.equals("Superdry")) name = "Superdry2";
        if (name.toUpperCase().equals("UCC国际洗衣")) {
            if (originalName.length() > 7) {
                name = originalName.replaceAll("洗衣", "");
                if (name.length() >= 10) {
                    name = name.replaceAll("\\(", "");
                    name = name.replaceAll("\\)", "");
                    name = name.substring(0, 9);
                }
            }
        }
        // 去掉空格
        name = name.replaceAll("\\s+", "");

        // 去重名
        // Offwhite
        if (name.equals("Offwhite")) name = "Offwhit" + AddressHelper.getRandomStr(2);
        // UCC国际洗衣
        if (name.equals("UCC国际洗衣")) name = "UCC国际洗衣" + AddressHelper.getRandomStr(2);
        // 伊蕾名店
        if (name.equals("伊蕾名店")) name = "伊蕾名店" + AddressHelper.getRandomStr(5);
        // 依尚街区
        if (name.equals("依尚街区")) name = "依尚街区" + AddressHelper.getRandomStr(5);
        // 利郎
        if (name.equals("利郎")) name = "利郎" + AddressHelper.getRandomStr(7);
        // 劲霸男装
        if (name.equals("劲霸男装")) name = "劲霸男装" + AddressHelper.getRandomStr(5);
        // 埃沃裁缝
        if (name.equals("埃沃裁缝")) name = "埃沃裁缝" + AddressHelper.getRandomStr(5);
        // 城市便捷酒店
        if (name.equals("城市便捷酒店")) name = "城市便捷酒店" + AddressHelper.getRandomStr(3);

        if (name.equals("城市空间·蘭会所")) name = "城市空间蘭会所" + AddressHelper.getRandomStr(2);
        if (name.equals("城市空间云会所足道")) name = "城市空间云会所" + AddressHelper.getRandomStr(2);
        if (name.equals("城门口老火锅中航")) name = "城门口老火锅中航" + AddressHelper.getRandomStr(1);
        if (name.equals("城门口老火锅")) name = "城门口老火锅" + AddressHelper.getRandomStr(3);
        if (name.equals("城门口老火锅太升")) name = "城门口老火锅太升" + AddressHelper.getRandomStr(1);
        if (name.equals("培贝体智能开发中心")) name = "培贝体智能开发" + AddressHelper.getRandomStr(2);
        if (name.equals("壹捷汽车服务")) name = "壹捷汽车服务" + AddressHelper.getRandomStr(3);
        if (name.equals("天空之城")) name = "天空之城" + AddressHelper.getRandomStr(5);
        if (name.equals("好声音量贩KTV")) name = "好声音量贩" + AddressHelper.getRandomStr(4);
        if (name.equals("如家酒店")) name = "如家酒店" + AddressHelper.getRandomStr(5);

        // 去掉符号，只保留中文、数字、字母
        name = name.replaceAll("[^\u4e00-\u9fa5a-zA-Z0-9]", "");

        return name;
    }

    /**
     * 压缩商铺名称中的字母
     *
     * @param name 名称
     * @return String
     */
    private static String handleLetter(String name) {
        Pattern pattern = Pattern.compile("([a-zA-Z]+)");
        Matcher matcher = pattern.matcher(name);
        String result = name;
        if (matcher.find()) {
            result = name.replaceAll("\\s+", "");
            String temp = matcher.group(1);
            if (temp.length() > 2) {
                temp = temp.substring(0, 2);
            }
            result = result.replaceAll("[a-zA-Z]+|\\.+|\\&+", temp.toUpperCase());
        }
        return result;
    }

    /**
     * 从门头照图片文件夹中获取商铺名称
     *
     * @param excelPath 头照图片文件夹
     * @return
     */
    @Override
    public List<Object> getShopNameFromFile(String excelPath, String doorPicFolder) {
        List<Object> userInfoList = null;
        try {
            userInfoList = getNameFromFile(excelPath);
            List<String> userNameFromFile = getNameFromFolder(doorPicFolder);

            System.out.println(userInfoList.size());
            System.out.println(userNameFromFile.size());

            Iterator it = userInfoList.iterator();
            while (it.hasNext()) {
                Map<String, String> userItem = (Map<String, String>) it.next();
                if (!userNameFromFile.contains(userItem.get("name"))) {
                    it.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userInfoList;
    }

    /**
     * 获取商户名称
     *
     * @param excelPath Excel文件路径
     * @return List
     * @throws Exception 异常
     */
    private List<Object> getNameFromFile(String excelPath) throws Exception {
        List<Object> shopInfoList = null;

        // 先从缓存中获取
        Object cacheObj = redisUtil.lGet(SY_CACHE_SHOP_INFO, 0, redisUtil.lGetListSize(SY_CACHE_SHOP_INFO));
        if (cacheObj instanceof List) {
            shopInfoList = (List<Object>) cacheObj;
        }
        if (shopInfoList != null && shopInfoList.size() > 0) {
            return shopInfoList;
        } else {
            shopInfoList = Lists.newArrayList();
        }


        // 从文件中读取
        File file = new File(excelPath);
        if (!file.exists()) {
            throw new Exception("文件不存在: " + excelPath);
        }
        List<Object> dataList = ExcelUtils.readExcel(excelPath, 1, 2, "ALL");
        if (dataList != null) {
            for (Object obj : dataList) {
                List<String> itemList = (List<String>) obj;
                if (StringUtils.isEmpty(itemList.get(0))) continue;

                // 商户名称、图片名称
                String name = itemList.get(1);
                String doorPicName = itemList.get(6);
                String tempName = doorPicName.substring(0, doorPicName.lastIndexOf("."));
                if (!name.equals(tempName)) {
                    name = tempName;
                }

                // 商户地址
                String province = itemList.get(2);
                String city = itemList.get(3);
                String area = itemList.get(4);
                String address = itemList.get(5);

                Map<String, String> itemMap = Maps.newHashMap();
                itemMap.put("name", name);
                itemMap.put("province", province);
                itemMap.put("city", city);
                itemMap.put("area", area);
                itemMap.put("address", address);

                String provinceCode = addressHelper.getProvinceCode(province);
                String cityCode = addressHelper.getCityCode(provinceCode, city);
                String areaCode = addressHelper.getAreaCode(cityCode, area);
                itemMap.put("provinceCode", provinceCode);
                itemMap.put("cityCode", cityCode);
                itemMap.put("areaCode", areaCode);

                // 过滤掉不能用的
                if (StringUtils.isEmpty(name) || StringUtils.isEmpty(provinceCode) ||
                        StringUtils.isEmpty(cityCode) || StringUtils.isEmpty(areaCode)) {
                    log.error("getNameFromFile() 无法获取省市区编号，" + itemList);
                    continue;
                }
                shopInfoList.add(itemMap);
            }
            if (shopInfoList.size() > 0) {
                redisUtil.lSet(SY_CACHE_SHOP_INFO, shopInfoList);
            }
        }

        return shopInfoList;
    }

    /**
     * 从文件夹中获取商户名称
     *
     * @param path 文件夹路径
     * @return List
     */
    private List<String> getNameFromFolder(String path) {
        List<String> shopNameList = Lists.newArrayList();
        File root = new File(path);
        if (!root.exists()) {
            return shopNameList;
        }
        File[] fileAr = root.listFiles();
        if (fileAr == null) {
            return shopNameList;
        }
        List<File> fileList = Lists.newArrayList(fileAr);
        fileList.forEach(item -> {
            String fileName = item.getName();
            if (fileName.contains(".xlsx")) {
                return;
            }
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            shopNameList.add(fileName);
        });

        return shopNameList;
    }


}
